package com.example.day01_weather.net;

import com.example.day01_weather.api.ApiService;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 */
public class HttpManger {
    private static HttpManger instance;

    public static HttpManger getInstance() {
        if(instance==null){
            synchronized (HttpManger.class){
                if (instance==null){
                    instance=new HttpManger();
                }
            }
        }
        return instance;
    }

    private ApiService apiService;

    public ApiService getApiService() {
        if(apiService==null){
            apiService=getRetrofit().create(ApiService.class);
        }
        return apiService;
    }
    public ApiService getLanApiService() {
        if(apiService==null){
            apiService=getLanRetrofit().create(ApiService.class);
        }
        return apiService;
    }
    public Retrofit getLanRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(getOkHttpClient())
                .baseUrl(ApiService.BASE_W_UEL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit;
    }
    public Retrofit getRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(getOkHttpClient())
                .baseUrl(ApiService.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit;
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient build = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new LoginInterceptot())
                .build();
        return build;
    }


    private class LoginInterceptot implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            builder.addHeader("Authorization","APPCODE 165b20d2a1a04e20a5e9e19f3b2200c2");
            Request build = builder.build();
            Response proceed = chain.proceed(build);
            return proceed;
        }
    }
}
